const xss = require('xss');

const xssHandler = () => {
  return async (ctx, next) => {
    try {
      const body = ctx.request.body;
      const deep = obj => {
        if (typeof obj == 'object' && obj !== null) {
          for (let key in obj) {
            obj[key] = deep(obj[key]);
          }
        } else {
          if (typeof obj == 'string') {
            obj = xss(obj);
          }
        }
        return obj;
      };
      deep(body);
      await next();
    } catch (err) {
      throw new Error(err);
    }
  };
};

module.exports = xssHandler;
